package top.bugger168.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.bugger168.ucenter.mapper.XcMenuMapper;
import top.bugger168.ucenter.model.dto.AuthParamsDto;
import top.bugger168.ucenter.model.dto.XcUserExt;
import top.bugger168.ucenter.model.po.XcMenu;
import top.bugger168.ucenter.service.AuthService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户服务impl
 *
 * @author wanghaidong
 * @date 2023/08/28
 */
@Slf4j
@Service
public class UserServiceImpl implements UserDetailsService {

    @Resource
    XcMenuMapper menuMapper;
    @Resource
    ApplicationContext applicationContext;

    /**
     *  根据账号查询用户信息
     * @param s  账号
     * @return org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        AuthParamsDto authParamsDto;
        try {
            //将认证参数转为AuthParamsDto类型
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            log.info("认证请求不符合项目要求:{}",s);
            throw new RuntimeException("认证请求数据格式不对");
        }

        // 认证类型,password,wx等
        String authType = authParamsDto.getAuthType();

        // 根据认证类型从spring容器中取出指定的bean
        String beanName = authType + "_authservice";
        AuthService authService = applicationContext.getBean(beanName,AuthService.class);
        // 调用统一认证接口
        XcUserExt user = authService.execute(authParamsDto);

        return getUserPrincipal(user);
    }

    /**
     *  查询用户信息
     * @param user  用户id，主键
     * @return top.bugger168.ucenter.model.po.XcUser 用户信息
     */
    public UserDetails getUserPrincipal(XcUserExt user){
        String password = user.getPassword();
        //查询用户权限
        List<XcMenu> xcMenus = menuMapper.selectPermissionByUserId(user.getId());
        List<String> permissions = new ArrayList<>();
        if(xcMenus.size()<=0){
            //用户权限,如果不加则报Cannot pass a null GrantedAuthority collection
            permissions.add("p1");
        }else{
            xcMenus.forEach(menu-> permissions.add(menu.getCode()));
        }
        //将用户权限放在XcUserExt中
        user.setPermissions(permissions);

        //为了安全在令牌中不放密码
        user.setPassword(null);
        //将user对象转json
        String userString = JSON.toJSONString(user);
        String[] authorities = permissions.toArray(new String[0]);
        return User.withUsername(userString).password(password).authorities(authorities).build();

    }

}